/****************************************************************
 *This file is verity_func.c
 ****************************************************************/

#include "include.h"

/****************************************************************
 *This function is calculate lrc
 *	(1)calculate lrc_buff's lrc value
 *
 *parameter meaning
 *	(1)lrc_buff : lrc_buff
 *	(2)lrc_length : lrc_buff len
 ****************************************************************/
 unsigned char calculate_lrc(const unsigned char *lrc_buff, unsigned int lrc_length)
{
	unsigned char calculate_return;
	unsigned int temp_i;

	//init inner value
	calculate_return = 0;
	temp_i = 0;

	//calculate lrc value
	for(temp_i = 0 ; temp_i < lrc_length ; temp_i ++)
	{
		calculate_return += lrc_buff[temp_i];
	}

	//return calculate lrc value
	return calculate_return;
}

/****************************************************************
 *This function is verity_frame lrc
 *	(1)verity frame lrc byte correct or incorrect
 *
 *parameter meaning
 *	(1)arg : user write parameter correspond arg to this function.
 *	(2)len : arg's length.
 *	(3)return_arg:master_control_func execute result.
 *	(4)return_len : return_arg parameter len
 ****************************************************************/
unsigned char verity_frame(const unsigned char *arg, unsigned int len, unsigned char *return_arg, unsigned int *return_len)
{
	unsigned char temp_i;
	unsigned int temp_j;
	unsigned int temp_k;

	return_arg = return_arg;
	return_len = return_len;
	len = len;

	//verity frame head
	if((arg[0] == FRAME_HEAD_ONE) && (arg[1] == FRAME_HEAD_TWO) && (arg[2] == ADDR_ZERO) && (arg[3] == ADDR_ZERO))
    {
		//get frame data field length
		temp_j = 0;
		temp_j = arg[4];
		temp_j =( temp_j << 8) + arg[5];
		temp_j += 6;

        //buffer length err
        if(temp_j > 5000){
            return FRAME_INCORRECT;
        }

		//verity frame end
		if((arg[temp_j + 1] == FRAME_END_ONE) && (arg[temp_j + 2] == FRAME_END_TWO))
		{
			//verity frame lrc data
			temp_k = arg[4];
			temp_k <<= 8;
			temp_k |= arg[5];
			temp_i = calculate_lrc(&(arg[6]), temp_k);
			if(temp_i == arg[temp_j])
			{
				//return verity correct
				return  FRAME_CORRECT;
			}
			else
			{
				//return verity incorrect
				return  FRAME_INCORRECT;
			}
		}
		else
		{
			//return verity incorrect
			return  FRAME_INCORRECT;
		}
	}
	else
	{
		//return verity incorrect
		return  FRAME_INCORRECT;
	}
}

